import { useContext, useEffect, useMemo } from 'react';
import { Search } from '../../baseComponent';
import { ModalContext, Table, TableInstance } from '../../functionalComponent';
import { emptyFn, Layout, iup, useApi, useRefCallback } from '../../util';
import { getPrintServer } from './service';
import { ControlType, FANRUANOPTIONS, PLATFORMOPTIONS, PREVIEW_TYPE } from './static';
import { info, SharePolicyEnum, wfAlert, wfModal } from './util';

/**
 * 审批流发起相关参数
 */
const global: { printParams: any; close?: Function; modalIns?: any } = {
  printParams: null,
  close: emptyFn,
  modalIns: null
};

interface Item {
  [key: string]: string | undefined;
}
/**
 * 对数组中的对象进行模糊匹配（前端）
 * @param filterDataObj 被匹配的数组中的每一项
 * @param searchStr 关键词
 * @param keysToMatch 过滤字段
 */
function fuzzyMatchObject(filterDataObj: Item, searchStr: string, keysToMatch: string[]): boolean {
  const pattern = new RegExp(searchStr, 'i');
  for (const key of keysToMatch) {
    const value = filterDataObj[key];
    if (value && pattern.test(value)) {
      return true;
    }
  }
  return false;
}

/**
 * 发起打印弹窗
 * @constructor
 */
function PrintContent() {
  const { printParams } = global;
  const tableRef = useApi<TableInstance>();
  const modalCtx = useContext(ModalContext);
  const onSearchHandler = useRefCallback((value) => {
    tableRef.current.getApi().filter((item) => fuzzyMatchObject(item, value, ['name']));
  });
  // 确认发起打印
  const validDataAndStartFlow = useRefCallback(async () => {
    const {
      printParams: { batchPrintList, source_sys }
    } = global;
    const selectData = tableRef.current.getApi().getSelectedData()[0];
    if (!selectData) {
      await wfAlert(info.alertTitle, info.selectTemplate);
      return;
    }
    switch (selectData.controlType) {
      case ControlType.FanRuan: {
        const printList = batchPrintList.map((item) => ({
          url: iup.getAbsoluteUrl(`${item.url}`),
          bizId: item.bizId
        }));
        const res = await getPrintServer();
        const params = {
          viewlet: selectData.fileName,
          token: iup.getUser()?.accessToken ?? null,
          bizCode: selectData.bizCode,
          source_sys: source_sys,
          bizDataParam: JSON.stringify(printList)
        };
        if (res.code === 0) {
          iup.open(
            `http://${res.data}/webroot/decision/view/report`,
            selectData.previewType !== PREVIEW_TYPE.PAGING ? { ...params, op: selectData.previewType } : params
          );
        } else {
          await wfAlert(info.printError, res.message);
        }
        break;
      }
      case ControlType.Platform: {
        iup.open('/print', {
          microAppName: 'printDesign',
          appTitle: '打印预览',
          id: JSON.stringify(batchPrintList),
          templateId: selectData.id,
          bizCode: selectData.bizCode
        });
        break;
      }
      default: {
        await wfAlert(info.printError, '暂不支持该类型的打印');
      }
    }
  });

  useEffect(() => {
    global.modalIns = modalCtx.ins;
    modalCtx.ins.setApi({
      invokeOkHandler: validDataAndStartFlow,
      invokeCancelHandler: async () => {
        await global.printParams.cancelback?.();
        global.close?.();
      }
    });
    tableRef.current.getApi().setSelected(0);
  }, []);

  const compProps = useMemo<any>(() => {
    const columnProps = {
      sortable: false,
      resizable: false,
      columnSort: false
    };
    return {
      labelStyle: {
        width: 65,
        marginLeft: '6px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center'
      },
      tableProps: {
        headerHeight: 32,
        rowHeight: 30,
        style: { border: '1px solid var(--border-color-split, #f0f0f0)' },
        columns: [
          {
            ...columnProps,
            header: info.templateCode,
            dataIndex: 'templateCode'
          },
          {
            ...columnProps,
            header: info.name,
            tooltip: true,
            dataIndex: 'name'
          },
          {
            ...columnProps,
            header: info.remark,
            tooltip: true,
            dataIndex: 'remark'
          },
          {
            ...columnProps,
            header: info.sharePolicy,
            tooltip: ({ row }) => {
              const sharePolicy = row.sharePolicy;
              return sharePolicy === SharePolicyEnum.GROUP
                ? info.group
                : sharePolicy === SharePolicyEnum.CU
                ? info.cu
                : sharePolicy === SharePolicyEnum.ORG
                ? info.org
                : '';
            },
            dataIndex: 'sharePolicy',
            width: 90,
            render: ({ row }) => {
              const sharePolicy = row.sharePolicy;
              return sharePolicy === SharePolicyEnum.GROUP
                ? info.group
                : sharePolicy === SharePolicyEnum.CU
                ? info.cu
                : sharePolicy === SharePolicyEnum.ORG
                ? info.org
                : '';
            }
          },
          {
            ...columnProps,
            header: info.shareTenant,
            tooltip: ({ row }) => {
              const sharePolicy = row.sharePolicy;
              return sharePolicy === SharePolicyEnum.CU
                ? row.shareTenantName
                : sharePolicy === SharePolicyEnum.ORG
                ? row.shareOrgName
                : '';
            },
            render: ({ row }) => {
              const sharePolicy = row.sharePolicy;
              return sharePolicy === SharePolicyEnum.CU
                ? row.shareTenantName
                : sharePolicy === SharePolicyEnum.ORG
                ? row.shareOrgName
                : '';
            }
          },
          {
            ...columnProps,
            header: info.previewType,
            width: 130,
            flex: 1,
            dataIndex: 'previewType',
            editor: {
              xtype: 'select',
              nameField: 'previewName',
              request: async (row) => {
                return row.controlType === ControlType.FanRuan ? FANRUANOPTIONS : PLATFORMOPTIONS;
              }
            }
          }
        ],
        dataSource:
          printParams.data?.map((item: any) => ({
            ...item,
            previewType: item.controlType === ControlType.FanRuan ? PREVIEW_TYPE.PAGING : PREVIEW_TYPE.DEFAULT,
            previewName:
              item.controlType === ControlType.FanRuan
                ? FANRUANOPTIONS.find((option) => option.value === PREVIEW_TYPE.PAGING)?.label
                : PLATFORMOPTIONS.find((option) => option.value === PREVIEW_TYPE.DEFAULT)?.label
          })) || []
      }
    };
  }, []);

  return (
    <Layout style={{ height: 400, padding: '5px 12px' }}>
      <Layout direction="row" style={{ width: '90%', margin: '12px 0' }}>
        <Search placeholder={info.searchEmptyText} allowClear onSearch={onSearchHandler} />
      </Layout>
      <Layout.Flex>
        <Table ref={tableRef} showRowNumber {...compProps.tableProps} />
      </Layout.Flex>
    </Layout>
  );
}

/**
 * 发起打印
 * @param props 属性
 */
export async function openPrintModal({ ...props }) {
  global.printParams = props;
  global.printParams.startFlowParam = {};
  global.close = () => {
    global.close = emptyFn;
    global.modalIns?.destroy();
    global.modalIns = null;
  };
  await wfModal({
    title: info.createPrintTitile,
    content: <PrintContent />,
    width: 750
  });
}
